<template>
  <view class="container">
    <!-- Header -->
    <view class="header">
      <view class="header-content">
        <text class="title">卖电瓶车</text>
        <p></p>
        <text class="subtitle">快速估价，轻松出售</text>
      </view>
    </view>

    <!-- 预估可卖 -->
    <view class="valuation-box">
      <view class="valuation-title">预估可卖</view>
      <view class="valuation-price">{{ state.valuationPrice }}</view>
    </view>

    <!-- 取件信息 -->
    <view class="pickup-info">
      <view class="pickup-item">
        <text class="pickup-label">取件地址</text>
        <view class="pickup-value">
          <input
            v-model="state.pickupAddress"
            placeholder="添加地址信息"
            @click="methods.showPopup"
            class="input-field"
          />
        </view>
      </view>
      <view class="pickup-item">
        <text class="pickup-label">上门时间</text>
        <view class="pickup-value">
          <input
            v-model="state.pickupTime"
            placeholder="请选择上门时间"
            @click="methods.showDatePicker"
            class="input-field"
          />
        </view>
      </view>
    </view>

    <!-- 我的电动车 -->
    <view class="my-electric-car">
      <button type="primary" class="car-button" @click="methods.chooseCarSpec">
        选择电动车规格
      </button>
      <text class="note">* 电动车过多请直接联系在线客服</text>
      <!-- 显示选择的电动车规格 -->
      <view class="car-spec">
        <text v-if="state.selectedBrand || state.selectedBattery || state.selectedVoltage || state.selectedAppearance">
          已选择：
          {{ state.selectedBrand || '无' }} -
          {{ state.selectedBattery || '无' }} -
          {{ state.selectedVoltage || '无' }} -
          {{ state.selectedAppearance || '无' }}
        </text>
      </view>
    </view>

    <!-- 用户协议 -->
    <view class="user-agreement">
      <checkbox-group @change="methods.onAgreementChange">
        <label class="agreement-label">
          <checkbox value="agree" :checked="state.agreementChecked" class="custom-checkbox" />
          {{ state.agreementChecked ? '已阅读并同意《用户服务协议》' : '阅读并同意《用户服务协议》' }}
        </label>
      </checkbox-group>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button">
      <button
        type="primary"
        class="submit-button"
        @click="submit"
        :disabled="!canSubmit"
      >
        回收换钱
      </button>
    </view>

    <!-- 弹窗 -->
    <view v-if="state.popupVisible" class="overlay">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">取件信息</text>
        </view>
        <view class="popup-item">
          <text class="popup-label">回收人：</text>
          <input
            v-model="state.recyclingPerson"
            placeholder="请输入回收人姓名"
            class="input-field"
          />
        </view>
        <view class="popup-item">
          <text class="popup-label">手机号：</text>
          <input
            v-model="state.phoneNumber"
            placeholder="请输入手机号码"
            class="input-field"
          />
        </view>
        <view class="popup-item">
          <text class="popup-label">地区：</text>
          <input
            v-model="state.region"
            placeholder="请输入地区"
            class="input-field"
          />
        </view>
        <view class="popup-item">
          <text class="popup-label">详情地址：</text>
          <input
            v-model="state.addressDetails"
            placeholder="请输入详细地址"
            class="input-field"
          />
        </view>
        <view class="popup-buttons">
          <button type="default" class="popup-button" @click="methods.savePopup">
            保存
          </button>
          <button type="default" class="popup-button" @click="state.popupVisible = false">
            关闭
          </button>
        </view>
      </view>
    </view>

    <!-- 时间选择器 -->
    <view v-if="state.datePickerVisible" class="overlay">
      <view class="date-picker-content">
        <view class="picker-header">
          <text class="picker-title">选择上门时间</text>
        </view>
        <view class="picker-row">
          <text class="picker-label">日期：</text>
          <picker mode="date" @change="methods.bindDateChange">
            <view class="picker-item">{{ state.dateValue || '请选择日期' }}</view>
          </picker>
        </view>
        <view class="picker-row">
          <text class="picker-label">时间：</text>
          <picker mode="time" @change="methods.bindTimeChange">
            <view class="picker-item">{{ state.timeValue || '请选择时间' }}</view>
          </picker>
        </view>
        <view class="picker-buttons">
          <button
            type="default"
            class="picker-button"
            @click="state.datePickerVisible = false"
          >
            取消
          </button>
          <button
            type="primary"
            class="picker-button"
            @click="methods.confirmDatePicker"
          >
            确定
          </button>
        </view>
      </view>
    </view>

    <!-- 电动车规格选择弹窗 -->
    <view v-if="state.carSpecPopupVisible" class="overlay">
      <view class="car-spec-content">
        <view class="spec-header">
          <text class="spec-title">电动车规格</text>
        </view>
        <view class="spec-item">
          <text class="spec-label">品牌：</text>
          <picker
            mode="selector"
            :range="state.carBrands"
            @change="methods.bindBrandChange"
          >
            <view class="picker-item">
              {{ state.selectedBrand || '请选择品牌' }}
            </view>
          </picker>
        </view>
        <view class="spec-item">
          <text class="spec-label">电池情况：</text>
          <picker
            mode="selector"
            :range="state.batterySituations"
            @change="methods.bindBatteryChange"
          >
            <view class="picker-item">
              {{ state.selectedBattery || '请选择电池情况' }}
            </view>
          </picker>
        </view>
        <view class="spec-item">
          <text class="spec-label">电压容量：</text>
          <picker
            mode="selector"
            :range="state.voltageCapacities"
            @change="methods.bindVoltageChange"
          >
            <view class="picker-item">
              {{ state.selectedVoltage || '请选择电压容量' }}
            </view>
          </picker>
        </view>
        <view class="spec-item">
          <text class="spec-label">外观情况：</text>
          <picker
            mode="selector"
            :range="state.appearanceSituations"
            @change="methods.bindAppearanceChange"
          >
            <view class="picker-item">
              {{ state.selectedAppearance || '请选择外观情况' }}
            </view>
          </picker>
        </view>
        <view class="spec-buttons">
          <button
            type="primary"
            class="spec-button"
            @click="methods.saveCarSpec"
          >
            确认
          </button>
          <button
            type="default"
            class="spec-button"
            @click="state.carSpecPopupVisible = false"
          >
            取消
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';

// 模拟登录状态（替换为实际的登录状态逻辑）
const isUserLoggedIn = () => {
  return !!uni.getStorageSync('Token'); // 假设用户登录后会存储 token
};

// 封装状态
const state = reactive({
  pickupAddress: '',
  pickupTime: '',
  recyclingPerson: '',
  phoneNumber: '',
  region: '',
  addressDetails: '',
  popupVisible: false,
  datePickerVisible: false,
  dateValue: '',
  timeValue: '',
  agreementChecked: true,
  valuationPrice: '￥0',
  selectedBrand: '',
  selectedBattery: '',
  selectedVoltage: '',
  selectedAppearance: '',
  carBrands: ['小刀', '雅迪', '爱玛'],
  batterySituations: ['仅车架', '整车 + 锂电池', '整车 + 铅酸电池'],
  voltageCapacities: ['48V+20Ah', '60V+20Ah', '72V+20Ah'],
  appearanceSituations: ['外观完好', '外观磨损'],
});

// 方法工具
const methods = {
  showPopup() {
    state.popupVisible = true;
  },
  savePopup() {
    state.pickupAddress = `${state.region} - ${state.addressDetails}`;
    state.popupVisible = false;
  },
  showDatePicker() {
    state.datePickerVisible = true;
  },
  bindDateChange(e) {
    state.dateValue = e.detail.value;
  },
  bindTimeChange(e) {
    state.timeValue = e.detail.value;
  },
  confirmDatePicker() {
    state.pickupTime = `${state.dateValue} ${state.timeValue}`;
    state.datePickerVisible = false;
  },
  chooseCarSpec() {
    state.carSpecPopupVisible = true;
  },
  bindBrandChange(e) {
    state.selectedBrand = state.carBrands[e.detail.value];
  },
  bindBatteryChange(e) {
    state.selectedBattery = state.batterySituations[e.detail.value];
  },
  bindVoltageChange(e) {
    state.selectedVoltage = state.voltageCapacities[e.detail.value];
  },
  bindAppearanceChange(e) {
    state.selectedAppearance = state.appearanceSituations[e.detail.value];
  },
  saveCarSpec() {
    const minPrice = 100;
    const maxPrice = 2000;
    const randomPrice = Math.floor(Math.random() * (maxPrice - minPrice + 1) + minPrice);
    state.valuationPrice = `￥${randomPrice}`;
    state.carSpecPopupVisible = false;
  },
  onAgreementChange(e) {
    state.agreementChecked = e.detail.value.includes('agree');
  },
};

// 提交方法
const canSubmit = computed(() => {
  return state.agreementChecked && state.pickupAddress !== '' && state.pickupTime !== '';
});

const submit = () => {
  if (!canSubmit.value) return;
  // 定义接口参数
  const orderParams = {
    userId: uni.getStorageSync('userId') || '',
    orderAmount: parseFloat(state.valuationPrice.replace('￥', '')) || 0,
    orderAddr: state.pickupAddress,
    contactNums: state.phoneNumber,
    contactName: state.recyclingPerson,
    brand: state.selectedBrand,
    battery: state.selectedBattery,
    voltage: state.selectedVoltage,
    appearance: state.selectedAppearance
  };

  uni.showLoading();
  http.request({
    url: '/p/order/car/submit',
    method: 'POST',
    data: orderParams,
  })
  .then((response) => {
    if (response.code === '00000') {
      // 调用成功后跳转到预约成功页面
      uni.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          debugger;
          console.info(response.data);
          // 确保传递的数据是 JSON 字符串
          const data = encodeURIComponent(JSON.stringify(response.data));
          console.info(data);
          uni.navigateTo({
            url: `/pages/order/order_car?data=${data}`,
          });
        },
      });
    } else {
      uni.showToast({
        title: response.msg || '提交失败',
        icon: 'none',
      });
    }
  })
  .catch((error) => {
    uni.showToast({
      title: '请求失败，请稍后再试',
      icon: 'none',
    });
  });
};
</script>

<style lang="scss" scoped>
:root {
  --primary-color: #007aff;
  --error-color: #ff5a5f;
  --background-color: #f9f9f9;
  --padding-base: 20px;
}

.container {
  padding: var(--padding-base);
  background-color: var(--background-color);
}

.header {
  position: relative;
  width: 100%;
  height: 200px;
  background: linear-gradient(to right, #00c6ff, #0072ff);
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: var(--padding-base);

  .header-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: white;
    text-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);

    .title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .subtitle {
      font-size: 16px;
    }
  }
}

.valuation-box {
  background-color: white;
  padding: var(--padding-base);
  border-radius: 10px;
  margin-bottom: var(--padding-base);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .valuation-title {
    font-size: 18px;
    color: #333;
    margin-bottom: 10px;
  }

  .valuation-price {
    font-size: 32px;
    color: var(--error-color);
    font-weight: bold;
    text-align: center;
  }
}

.pickup-info {
  background-color: white;
  padding: var(--padding-base);
  border-radius: 10px;
  margin-bottom: var(--padding-base);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .pickup-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .pickup-label {
      font-size: 16px;
      color: #333;
      flex: 0 0 80px;
    }

    .pickup-value {
      flex: 1;
      padding-left: 10px;

      .input-field {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 14px;
      }
    }
  }
}

.my-electric-car {
  background-color: white;
  padding: var(--padding-base);
  border-radius: 10px;
  margin-bottom: var(--padding-base);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .car-button {
    width: 100%;
    margin-bottom: 10px;
  }

  .note {
    font-size: 12px;
    color: #999;
    margin-bottom: 10px;
  }

  .car-spec {
    font-size: 14px;
    color: #666;
  }
}

.user-agreement {
  background-color: white;
  padding: var(--padding-base);
  border-radius: 10px;
  margin-bottom: var(--padding-base);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .agreement-label {
    font-size: 14px;
    color: #333;

    .custom-checkbox {
      margin-right: 5px;
    }
  }
}

.bottom-button {
  padding: var(--padding-base);
  text-align: center;

  .submit-button {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 5px;
  }
}

// 弹窗样式
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  width: 90%;
  max-width: 400px;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .popup-header {
    padding: 15px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #eee;

    .popup-title {
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }
  }

  .popup-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;

    .popup-label {
      font-size: 14px;
      color: #333;
      flex: 0 0 80px;
    }

    .input-field {
      flex: 1;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 14px;
    }
  }

  .popup-buttons {
    display: flex;
    justify-content: space-between;
    padding: 15px;

    .popup-button {
      flex: 1;
      padding: 8px;
      border-radius: 5px;
      font-size: 14px;
      margin: 0 5px;
    }
  }
}

.date-picker-content {
  width: 90%;
  max-width: 400px;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .picker-header {
    padding: 15px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #eee;

    .picker-title {
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }
  }

  .picker-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;

    .picker-label {
      font-size: 14px;
      color: #333;
      flex: 0 0 80px;
    }

    .picker-item {
      flex: 1;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 14px;
    }
  }

  .picker-buttons {
    display: flex;
    justify-content: space-between;
    padding: 15px;

    .picker-button {
      flex: 1;
      padding: 8px;
      border-radius: 5px;
      font-size: 14px;
      margin: 0 5px;
    }
  }
}

.car-spec-content {
  width: 90%;
  max-width: 400px;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

  .spec-header {
    padding: 15px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #eee;

    .spec-title {
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }
  }

  .spec-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;

    .spec-label {
      font-size: 14px;
      color: #333;
      flex: 0 0 80px;
    }

    .picker-item {
      flex: 1;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 14px;
    }
  }

  .spec-buttons {
    display: flex;
    justify-content: space-between;
    padding: 15px;

    .spec-button {
      flex: 1;
      padding: 8px;
      border-radius: 5px;
      font-size: 14px;
      margin: 0 5px;
    }
  }
}
</style>